﻿
namespace SistemaLogistica.Windows.Forms.Almacen.Operaciones
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.EventArgs;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfFactura : MaestroDetalleSeguro, Observador, IRefrescar
    {
        public CwfFactura()
        {
            InitializeComponent();
            this.dgvDetalle.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvDetalle.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvDetalle.DataGridView.Rows.Remove(this.dgvDetalle.DataGridView.CurrentRow);
                        if (this.dgvDetalle.DataGridView.Rows.Count == 0)
                        {
                            this.dgvDetalle.DataGridView.Rows.Add();
                        }
                    }
                }
            }
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        protected override void InitialLoad()
        {
            try
            {
                lblUsuario.Text = Empresa.Usuario.Nombre;
                lblUsuario.Tag = Empresa.Usuario.IdEmpleado;
                LoadProveedores();
                this.MaestroBindingSource.DataSource = FacturaManager.Instancia.Listar();
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                OcultarColumnas();
                LoadDataGridView();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void LoadProveedores()
        {
            this.cmbProveedor.DisplayMember = "RazonSocial";
            this.cmbProveedor.ValueMember = "IdProveedor";
            this.cmbProveedor.DataSource = ProveedorManager.Instancia.Listar();

            this.cmbProveedores.DisplayMember = "RazonSocial";
            this.cmbProveedores.ValueMember = "IdProveedor";
            this.cmbProveedores.DataSource = ProveedorManager.Instancia.Listar();
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["Serie"].Visible = false;
            this.dgvMaestro.Columns["Numero"].Visible = false;
            this.dgvMaestro.Columns["Descripcion"].Visible = false;
            this.dgvMaestro.Columns["OrdenCompra"].Visible = false;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["IdFactura"].HeaderText = "Factura";
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Bien";
            colummn.HeaderText = "Bien";
            colummn.Width = 300;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);
            colummn.ColumnNext = 3;

            colummn = new CustomColumnDataGridView();
            colummn.Name = "UnidadMedida";
            colummn.HeaderText = "UnidadMedida";
            colummn.ControlType = CustomControlType.TextBox;
            colummn.ReadOnly = true;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 80;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Precio";
            colummn.HeaderText = "Precio";
            colummn.Width = 80;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Rows.Add();
            this.dgvDetalle.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            Factura factura = this.MaestroBindingSource[e.RowIndex] as Factura;

            if (factura != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);

                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "Nº: " + factura.IdFactura.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "Nº: " + factura.IdFactura.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, "P: " + (factura.OrdenCompra.Proveedor ?? new Proveedor()).RazonSocial ?? string.Empty, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "F: " + factura.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "F: " + factura.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                }
            }
        }

        protected override void EventoNuevo()
        {
            this.dtpFecha.Enabled = false;
            this.dtpFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtpFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.dtpFecha.Enabled = true;
            this.dtpFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        private void dgvDetalle_BeforeShowControl(object sender, BeforeShowControlEventArg e)
        {
            switch (e.Cell.ColumnIndex)
            {
                case 0: // Cargar Bien
                    try
                    {
                        ComboBox cmbA = e.Control as ComboBox;
                        cmbA.DataSource = null;
                        cmbA.DisplayMember = "Nombre";
                        cmbA.ValueMember = "IdBien";
                        cmbA.DataSource = BienManager.Instancia.Listar();
                    }
                    catch (Exception ex)
                    {
                        Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        private void dgvDetalle_EnterKeyPress(object sender, EnterKeyPressEventArg e)
        {
            switch (e.ColumnIndex)
            {
                case 0: // Vehiculo
                    if (!string.IsNullOrEmpty(e.Text))
                    {
                        List<Bien> bien = BienManager.Instancia.Buscar(e.Text);
                        if (bien != null)
                        {
                            this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[1].Value = bien[0].UnidadMedidia.Abreviatura;
                        }
                        else
                        {
                            e.Handle = false;
                        }
                    }
                    else
                    {
                        e.Handle = false;
                    }
                    break;
                 case 1://Cantidad
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    
                    break;
                case 3: // Precio
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    if (e.Handle)
                    {
                        if (this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[0].Tag != null)
                        {
                            int count = this.dgvDetalle.DataGridView.Rows.Count;
                            if (this.dgvDetalle.DataGridView.Rows[count - 1].Cells[0].Value != null)
                            {
                                if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea agregar un nuevo Detalle?") == DialogResult.Yes)
                                {
                                    this.dgvDetalle.DataGridView.Rows.Add();
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        protected override void LoadData(object obj)
        {
            Factura factura = obj as Factura;
            if (factura != null)
            {
                this.identificador = factura.IdFactura;
                this.dtpFecha.Value = factura.Fecha;
                this.txtNumero.Text = factura.Numero;
                this.txtSerie.Text = factura.Serie;
                this.cmbProveedor.SelectedValue = factura.OrdenCompra.Proveedor.IdProveedor;
                this.lblUsuario.Text = factura.Empleados.Nombre;
                this.lblUsuario.Tag = factura.Empleados.IdEmpleado;
                this.txtDescripcion.Text = factura.Descripcion;

                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleFactura d in factura.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[3].Value = d.Precio;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        FacturaManager.Instancia.Registrar(GetFactura());
                        break;
                    case EstadoActual.Editar:
                        FacturaManager.Instancia.Modificar(GetFactura());

                        #region EditarNotaIngreso

                        NotaIngreso notaIngreso = new NotaIngreso();
                        notaIngreso = NotaIngresoManager.Instancia.ObtenerPorFactura(Convert.ToInt32(identificador));
                        if (notaIngreso != null)
                        {
                            notaIngreso.Detalle.Clear();
                            foreach (var item in GetFactura().Detalle)
                            {
                                notaIngreso.Detalle.Add(new DetalleNotaIngreso
                                {
                                    Bien = new Bien { IdBien = item.Bien.IdBien },
                                    Cantidad = item.Cantidad,
                                    Precio = item.Precio
                                });
                            }
                            NotaIngresoManager.Instancia.Modificar(notaIngreso);
                        }

                        #endregion

                        break;
                    case EstadoActual.Eliminar:
                        FacturaManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
            return result;
        }

        private Factura GetFactura()
        {
            Factura factura = new Factura
            {
                IdFactura = Convert.ToInt32(this.identificador),
                Fecha = this.dtpFecha.Value,
                OrdenCompra = new OrdenCompra { IdOrdenCompra = Convert.ToInt32(cmbNumero.SelectedValue) },
                Empleados = new Empleados { IdEmpleado = Empresa.Usuario.IdEmpleado },
                Serie = txtSerie.Text,
                Numero = txtNumero.Text,
                Descripcion = this.txtDescripcion.Text
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    factura.Detalle.Add(new DetalleFactura
                    {
                        Bien = new Bien { IdBien = Convert.ToInt32(row.Cells[0].Tag) },
                        Cantidad = Convert.ToDecimal(row.Cells[2].Value),
                        Precio = Convert.ToDecimal(row.Cells[3].Value)
                    });
                }
            }
            return factura;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[3].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbProveedor.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbProveedor, "Seleccionar Proveedor.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbProveedor, string.Empty);
            }
            if (string.IsNullOrEmpty(this.txtSerie.Text.Trim()))
            {
                this.errValidator.SetError(this.txtSerie, "Ingresar Serie.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.txtSerie, string.Empty);
            }
            if (string.IsNullOrEmpty(this.txtNumero.Text.Trim()))
            {
                this.errValidator.SetError(this.txtNumero, "Ingresar Numero.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.txtNumero, string.Empty);
            }
            int contador1 = 0;
            int contador2 = 0;
            foreach (DataGridViewRow row in dgvDetalle.DataGridView.Rows)
            {
                if (row.Cells[0].Tag == null) continue;
                if (ValidateData(row.Index)) contador1++;
                else contador2++;
            }
            if (!(contador1 != 0 && contador2 == 0 && dgvDetalle.DataGridView.Rows.Count > 0))
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, "Debe existir proudctos e ingresados correctamente.");
                result = false;
            }

            return result;
           
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            LoadDataGridView();
            base.ClearControls();
        }

        private void txtSerie_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                e.Handled = true;
                txtSerie.Text = txtSerie.Text.PadLeft(4, '0');
                txtNumero.Focus();
            }
        }

        private void txtNumero_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                txtNumero.Text = txtNumero.Text.PadLeft(7, '0');
                this.txtDescripcion.Focus();

            }
        }
    
        private void cmbProveedor_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.cmbNumero.DataSource = OrdenCompraManager.Instancia.ListarIDPorProveedor(Convert.ToInt32(this.cmbProveedor.SelectedValue));
        }

        private void LoadDataOrdenCompra(OrdenCompra  ordenCompra)
        {
            if (ordenCompra != null)
            {
                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleOrdenCompra d in ordenCompra.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        private void cmbNumero_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbNumero.SelectedValue != null)
            {
                OrdenCompra OrdenCompra = OrdenCompraManager.Instancia.ObtenerPorID(Convert.ToInt32(this.cmbNumero.SelectedValue));
                if (OrdenCompra != null)
                    LoadDataOrdenCompra(OrdenCompra);
            }
        }

        private void cmbProveedores_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbProveedores.SelectedIndex != -1)
            {
                try
                {
                    this.MaestroBindingSource.DataSource = FacturaManager.Instancia.BuscarPorProveedor(Convert.ToInt32(this.cmbProveedores.SelectedValue));
                    this.dgvMaestro.DataSource = this.MaestroBindingSource;
                    this.dgvMaestro.Focus();
                }
                catch (Exception ex)
                {
                    Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
                }
            }
        }

        #region Miembros de Observador

        public void Notificar(object mensaje)
        {
            LoadProveedores();
        }

        #endregion

        #region Miembros de IRefrescar

        public void Refrescar()
        {
            InitialLoad();
        }

        #endregion
    }
}
